# -* - coding: UTF-8 -* -
#import sys
#reload(sys)
#sys.setdefaultencoding('utf8')

import string
from time import sleep
from task import *
import logging
import json

#支持delete及update命令,条件仅支持并的关系,只支持=条件
#update a=1,b=2,c=3 where orderId=12313 limit 1
#delete where orderId=12323 limit 1

class SQLCommand():  
	def __init__(self,sql):  
		self.command = ''
		self.limit=1#执行的上限
		self.count=0#已经处理的条数
		self.where={}
		self.fields={}
		try:
			self.__parse(sql)
		except Exception as e:
			pass
	
	#将字符串解析成字典
	def __parse_dict(self,str):
		ret={}
		for s in str.strip().split(','):
			p=s.split('=')
			if len(p)<=2:
				ret[p[0]]=p[1]
		return ret
	def __string_dict(self,data):
		ret=''
		for k,v in data.items():
			ret=ret+k+'='+v+','
		return ret.lstrip(',')	
	#解析类SQL
	def __parse(self,sql):
		i=1
		list=sql.strip().split(' ')
		self.command=list[0].lower()
		if self.command=='update':
			self.fields=self.__parse_dict(list[i])
			i=i+1
		while i <len(list)-1:
			word=list[i].lower()
			if list[i+1].strip()!='':
				if word=='where':
					self.where=self.__parse_dict(list[i+1])
				elif word=='limit':
					self.limit=int(list[i+1])
			i=i+1
	#执行命令处理
	def execute(self,task):
		if self.check_where(task.toArray()):
			self.count=self.count+1
			if self.command=='delete':
				return 0
			elif self.command=='update':
				task.update(fields)
				return 1
		else:
			return 1
			
	#命令是否已经完成
	def is_finish(self):
		return self.count>=self.limit
		
	#是否符合条件
	def check_where(self,task):
		for k,v in self.where.items():
			if k in task and task[k].lower()!=v.lower():
				return False
		return True
	#**
	# Json字符串生成任务
	# @access public
	# @return mixed
	#/
	def fromJson(self,s):
		data=json.loads(s)
		if data and data.get('command',False):
			self.command=data.get('command','')
			self.limit=data.get('limit','')
			self.count=data.get('count','')
			self.where=data.get('where',None)
			self.fields=data.get('fields',None)
	
	#*
	# 任务转换成Json字符串
	# @access public
	# @return string
	#/
	def toJson(self):
		ret={}
		ret['command']=self.command
		ret['limit']=self.limit
		ret['count']=self.count
		ret['where']=self.where
		ret['fields']=self.fields
		return json.dumps(ret)